#!/usr/bin/python
# -*- encoding:utf-8 -*-

"""
    此工程提供对外WebJSON接口，方便外部使用程序操作linux系统管理sftp用户
    previous preparation:
        pip install fastapi uvicorn -i https://mirrors.aliyun.com/pypi/simple/
    （当前使用FastApi来代替Flask模块实现WebJson工程，该py文件等同于JavaWeb项目的一个@Controller）
    【故对于多个Controller存放不同接口，应创建多个py启动类】
"""
import sys

sys.path.append("..")
from fastapi import FastAPI, Header
import uvicorn
from pydantic import BaseModel  # fastapi的一个依赖,需要从pydantic中引入
from sftp_account_manage.com.entity.SftpUser import SftpUSER
from sftp_account_manage.com.util.MailUtil import MailUtil
from fastapi.responses import JSONResponse
import json
import os

app = FastAPI()


# 定义允许识别的json请求参数
class EchoArgs(BaseModel):  # 继承BaseModel
    oprate_type: str  # 定义操作类型，创建或删除用户
    username: str  # 被操作用户的账号
    password: str = None  # 被操作用户的登录口令，非必须参数(即已经初始化，默认有值)


# 1.body参数请求，载荷（payload）
@app.post("/sftp_user_mag")  # get不支持请求体,更换请求方法
async def postEchoApi(args: EchoArgs):  # 设置刚才定义的参数
    su = SftpUSER('sftp', '/home/sftp')
    rbody = {}
    if args.oprate_type == 'add':
        result, msg = su.create_user(args.username, args.password)
    elif args.oprate_type == 'del':
        result, msg = su.delete_user(args.username)
    else:
        rbody['result'] = False
        rbody['msg'] = '请求参数使用无效操作类型: {}'.format(args.oprate_type)
        return rbody
    rbody['result'] = result
    rbody['msg'] = msg
    return rbody  # 原样返回


# 定义允许识别的json请求参数
class RequestBodyA(BaseModel):  # 继承BaseModel
    receiver_mail_addr: str  # 定义操作类型，创建或删除用户
    mail_subject: str  # 被操作用户的账号
    mail_content: str  # 被操作用户的登录口令


@app.post('/sendmail')
async def sendmail(req: RequestBodyA, cd_ir: str = Header(None)):
    """
    获取headers中的某个header,需要声明一个变量。
    ------------- 1 begin -------------
    Header（None，convert_underscores=False即不将“_”转为“-”）
    假设变量设为cd_ir,则它能接收识别的header为: Cd_ir、cD_Ir等,  即只能识别下划线且大小写不敏感
    ------------- 1  end  -------------
    ------------- 2 begin -------------
    Header（None，convert_underscores=True即允许将“_”转为“-”），不加convert_underscores参数则默认为True
    它自动将下划线转为横杠，且大小写不敏感
    ------------- 2  end  -------------
    其他：
    json.loads(json_str) json字符串转换成字典
    json.dumps(dict) 字典转换成json字符串
    """
    content = {}
    headers = {}
    statusCode: int = -1
    msg: str = '身份核验不通过'
    if cd_ir is None or cd_ir != '147369':
        content['statusCode'] = statusCode
        content['msg'] = msg
        return JSONResponse(content=content, headers=headers)
    # 身份核验通过
    # # 开启业务流 # #
    m = MailUtil(req.receiver_mail_addr, req.mail_subject)
    ret = m.sendHtml(req.mail_content)
    if ret:
        statusCode = 1
        msg = "邮件发送成功"
    else:
        msg = "邮件发送失败"
    # # 结束业务流 # #
    content['statusCode'] = statusCode
    content['msg'] = msg
    headers['token'] = '111222333'
    return JSONResponse(content=content, headers=headers)


@app.get('/checkGroupUser/{group_name}')
async def check_memery(group_name: str):
    command_1 = 'cat /etc/group | awk -F \':\' \'($1==\"' + group_name + '\"){ print $3}\''
    rbody = {'msg': '组搜索结果不唯一，请输入完整的组名', 'statusCode': -1}
    result = os.popen(command_1)
    res = result.read()
    result_line_count = len(res.splitlines())
    if result_line_count != 1:
        return rbody
    else:
        gid = ''
        # index: int
        # index = 0
        for line in res.splitlines():
            # index += 1
            # rbody[str(index)] = line
            gid = line
            break
        # use the gid to obtain the username list
        command_2 = 'cat /etc/passwd | awk -F \':\' \'($4==\"' + gid + '\"){ print $1}\''
        user_name_list = []
        result_ = os.popen(command_2)
        res_ = result_.read()
        result_user_count = len(res_.splitlines())
        if result_user_count > 0:
            for line in res_.splitlines():
                user_name_list.append(line)
            rbody['msg'] = '该组下的用户有'
            rbody['userlist'] = user_name_list
        else:
            rbody['msg'] = '该组下未搜索到用户'
        rbody['statusCode'] = 1
        return rbody


if __name__ == '__main__':
    args = sys.argv
    """
        In linux:
        (Run command 1): nohup python3 sftp_manage.py -p 8086 > $Project_Absolute_Path/logs/sftp_manage.log 2>&1 &
        (Run command 2): cd $Project_Absolute_Path 
                         nohup python3 sftp_manage.py -p 8086 > ./logs/sftp_manage.log 2>&1 &
            args[0], sftp_manage.py
            args[1], -p
            args[2], 8080
        (Check run status): ps -ef | grep -v grep | grep sftp_manage.py | awk '{print $2}'
        (Count run process): ps -ef | grep -v grep | grep sftp_manage.py | wc -l
        (Kill this process): ps -ef | grep -v grep | grep sftp_manage.py | awk '{print $2}' | xargs kill -9
    """
    if len(args) == 3 and args[0] == 'sftp_manage.py' and args[1] == '-p':
        try:
            port = int(args[2])
            uvicorn.run(app=app,
                        host="0.0.0.0",
                        port=port,
                        workers=1)
        except BaseException as e:  # 如果发生异常，则返回False
            print('端口号设置有误，请更正(', e, ')')
    else:
        print('启动方式不正确, The correct startup way should like【python sftp_manage.py -p 8081】')
